#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/mod_devicetable.h>
#include <linux/gpio/consumer.h>
#include <linux/gpio.h>

unsigned int count;
struct fwnode_handle *child_fw = NULL;
struct gpio_desc *led[2];
int i = 0;
int num = 0;

// 平台设备初始化函数
static int my_platform_probe(struct platform_device *dev)
{
    printk("This is my_platform_probe\n");

    // 获取父设备节点的子设备节点数量
    count = device_get_child_node_count(&dev->dev);
    printk("count is %d\n", count);

    for (i = 0; i < count; i++)
    {
        // 获取下一个子设备节点
        child_fw = device_get_next_child_node(&dev->dev, child_fw);

        if (child_fw)
        {
            // 获取子设备节点中名为 "my-gpios" 的 GPIO 描述
            led[i] = fwnode_get_named_gpiod(child_fw, "my-gpios", 0, 0, "LED");
        }

        // 将 GPIO 描述转换为 GPIO 号
        num = desc_to_gpio(led[i]);
        printk("num is %d\n", num);
    }

    return 0;
}

// 平台设备的移除函数
static int my_platform_remove(struct platform_device *pdev)
{
    printk(KERN_INFO "my_platform_remove: Removing platform device\n");

    // 清理设备特定的操作
    // ...

    return 0;
}

const struct of_device_id of_match_table_id[] = {
    {.compatible = "mygpio"},
};

// 定义平台驱动结构体
static struct platform_driver my_platform_driver = {
    .probe = my_platform_probe,
    .remove = my_platform_remove,
    .driver = {
        .name = "my_platform_device",
        .owner = THIS_MODULE,
        .of_match_table = of_match_table_id,
    },
};

// 模块初始化函数
static int __init my_platform_driver_init(void)
{
    int ret;

    // 注册平台驱动
    ret = platform_driver_register(&my_platform_driver);
    if (ret)
    {
        printk(KERN_ERR "Failed to register platform driver\n");
        return ret;
    }

    printk(KERN_INFO "my_platform_driver: Platform driver initialized\n");

    return 0;
}

// 模块退出函数
static void __exit my_platform_driver_exit(void)
{
    // 注销平台驱动
    platform_driver_unregister(&my_platform_driver);

    printk(KERN_INFO "my_platform_driver: Platform driver exited\n");
}

module_init(my_platform_driver_init);
module_exit(my_platform_driver_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("fangchen");